'use strict';

const fs = require('fs-extra');
const path = require('path');
const Controller = require('egg').Controller;

class AdminController extends Controller {
  async index() {
    const { ctx } = this;
    await ctx.render('pc/admin.pug', {
    });
  }
  async upload() {
    const { ctx } = this;
    const file = ctx.request.files[0];
    const name = 'egg-multipart-test/' + path.basename(file.filename);
    let result;
    try {
      // 处理文件，比如上传到云端
      // result = await ctx.oss.put(name, file.filepath);
      result = {
        url: name,
      };
    } finally {
      // 需要删除临时文件
      // await fs.unlink(file.filepath);
    }

    ctx.body = {
      url: result.url,
      // 获取所有的字段值
      requestBody: ctx.request.body,
    };
  }
  async css() {
    const {ctx, app} = this;
    let fileName = ctx.request.query.name
    if (!fileName) {
      ctx.status = 404
      return 
    }
    let filePath = path.join(app.baseDir, '/app/css/' + fileName)
    
    try {
      let str = fs.readFileSync(filePath).toString()
      ctx.body = str
    } catch(e) {
      ctx.status = 500
    }
  }
}

module.exports = AdminController;
